const router = require('koa-router')()
const { exec } = require('../db')
// 列表查询 分页 模糊搜 keywords
router.get('/api/comments', async (ctx, next) => {
	const { page, size, keywords } = ctx.query
	let sql = ``
	if (keywords) {
		sql = `select * from comments where content like '%${keywords}%' limit ? offset ?;`
	} else {
		sql = `select * from comments limit ? offset ?;`
	}
	// 查询总数
	const count = await exec(`select count(id) as num from comments`)
	if (keywords) {
		const list = await exec(sql, [size * 1, (page - 1) * size])
		// 总数
		ctx.body = {
			code: 200,
			msg: 'success',
			data: { list, count: count[0].num }
		}
	} else {
		const list = await exec(sql, [size * 1, (page - 1) * size])
		ctx.body = {
			code: 200,
			msg: 'success',
			data: { list, count: count[0].num }
		}
	}
})

// 找作者
router.get('/api/getUser', async (ctx, next) => {
	const { userId } = ctx.query
	const userData = await exec(
		`select username, avatar from users where id = ?`,
		[userId]
	)
	ctx.body = userData
})

// 基于用户筛选文章 找文章
router.get('/api/searchBlogs', async (ctx, next) => {
	const { userId } = ctx.query
	const data = await exec(`select * from blogs where userId=?`, [userId])
	ctx.body = { code: 0, msg: 'success', data }
})

// 评论添加
// 列表查询 分页 模糊搜 keywords
router.post('/api/comments', async (ctx, next) => {
	// 结构赋值，相当于声明
	const { userId = 1, content, blogsId } = ctx.request.body
	const list = await exec(
		`insert into comments (userId, content, blogsId) values (?, ?, ?)`,
		[userId, content, blogsId]
	)
	if (list.affectedRows) {
		ctx.body = {
			code: 0,
			msg: 'success',
			data: list
		}
	} else {
		ctx.body = {
			code: -1,
			msg: 'fail'
		}
	}
})

// 评论编辑
router.put('/api/comments', async (ctx, next) => {
	// 结构赋值，相当于声明 id : 评论ID
	const { content, id } = ctx.request.body
	const updateList = await exec(`update comments set content=? where id=?`, [
		content,
		id
	])
	if (updateList.affectedRows) {
		ctx.body = {
			code: 0,
			msg: 'success',
			data: updateList
		}
	} else {
		ctx.body = {
			code: -1,
			msg: 'fail'
		}
	}
})
// 评论删除
router.delete('/api/comments', async (ctx, next) => {
	// 结构赋值，相当于声明 id : 评论ID
	const { id } = ctx.request.body
	const deleteList = await exec(`delete from comments where id=?`, [id])
	if (deleteList.affectedRows) {
		ctx.body = {
			code: 0,
			msg: 'success',
			data: deleteList
		}
	} else {
		ctx.body = {
			code: -1,
			msg: 'fail'
		}
	}
})

module.exports = router
